import React, { useEffect, useState } from 'react';
import ForEditor from 'for-editor';
import { Button, Input, Select, message } from 'antd';
import { getTags } from '@/api/exam/tags';
import { TagsItem } from '@/api/tags';
import { addPosts } from '@/api/posts';

const { Option } = Select;

export default function AddPosts() {
  const [title, setTitle] = useState('');
  const [tags, setTags] = useState([]);
  const [content, setContent] = useState('');
  const [tagsName, setTagsName] = useState<string[]>([]);
  useEffect(() => {
    getTags().then((res) => {
      setTagsName(res.data.map((it: TagsItem) => it.tagName));
    });
  }, []);
  const handleSubmit = () => {
    addPosts({
      title,
      tags,
      content,
      userID: sessionStorage.getItem('userID') ?? null
    }).then(() => {
      message.success('发布成功，请前往文章管理查看');
    });
  };
  return (
    <>
      <p style={{ display: 'flex', justifyContent: 'space-between' }}>
        <div>
          <p style={{ display: 'flex', marginBottom: '20px', alignItems: 'center' }}>
            <label>标题:</label>
            <Input onChange={(v) => setTitle(v.target.value)} style={{ width: '250px', marginLeft: '10px' }} />
          </p>
          <p style={{ display: 'flex', marginBottom: '20px', alignItems: 'center' }}>
            <label>标签:</label>
            <Select mode="tags" onChange={(v) => setTags(v)} style={{ width: '250px', marginLeft: '10px' }}>
              {tagsName?.map((it) => (
                <Option key={it}>{it}</Option>
              ))}
            </Select>
          </p>
        </div>
        <div>
          <Button type="primary" onClick={handleSubmit}>发布</Button>
        </div>
      </p>
      <ForEditor value={content} onChange={(value) => setContent(value)} />
    </>
  );
}
